package com.sk.waste.app.activitys

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import com.lc.smc.lib.annotations.LCBindView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCLogger
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.waste.app.R
import com.sk.waste.app.bases.BaseActiivity
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException

/**
 *  @time 2025/4/25  17:11
 *  @desc 找回密码
 */
class FindPassActivity : BaseActiivity() {

    @LCBindView(R.id.ac_register_phone)
    private lateinit var ettPhone: EditText

    @LCBindView(R.id.ac_register_code)
    private lateinit var ettCode: EditText

    @LCBindView(R.id.ac_resetpaas_password_new)
    private lateinit var ettPassNew: EditText

    @LCBindView(R.id.ac_register_getcode)
    private lateinit var bttCode: Button

    @LCBindView(R.id.ac_resetpass_submit)
    private lateinit var bttSave: Button

    private var countdown = 60
    private var handlerCountdown: Handler? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        setContentView(R.layout.activity_find_password)
        super.onCreate(savedInstanceState)
        setTitleColorLight(false)
        setBack()
        setTitleView("找回密码")
        initView()
    }

    fun initView() {

        bttCode.setOnClickListener {
            val phone = ettPhone.text.toString().trim()
            if (isNull(phone)) {
                showToast("请输入手机号！")
                return@setOnClickListener
            }
            getCode(phone)
        }

        bttSave.setOnClickListener {
            if (checkParams()) {
                val phone = ettPhone.text.toString()
                val code = ettCode.text.toString()
                val newPass = ettPassNew.text.toString()
                val params = JSONObject()
                params.put("phone", phone.trim())
                params.put("captcha", code.trim())
                params.put("password", newPass.trim())
                submitPass(params.toString())
            }
        }
    }

    fun checkParams(): Boolean {
        val phone = ettPhone.text.toString()
        val code = ettCode.text.toString()
        val newPass = ettPassNew.text.toString()
        if (TextUtils.isEmpty(phone)) {
            showToast("请输入手机号")
            return false
        }
        if (TextUtils.isEmpty(code)) {
            showToast("请输入验证码")
            return false
        }
        if (TextUtils.isEmpty(newPass)) {
            showToast("请输入新密码")
            return false
        }
        val regex = "^(?=.*[A-Za-z])(?=.*\\d).+$"
        if (newPass.length < 6 || !newPass.matches(Regex(regex))) {
            showToast("请输入6位以上的密码，包含字母和数字！")
            return false
        }
        return true
    }

    /**
     *  @time 2025/6/6  19:41
     *  @desc 获取验证码
     */
    private fun getCode(phone: String) {
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_GETCODE
        val params = JSONObject()
        params.put("phone", phone)

        showProgress()
        val httpUtil = OkHttpUtil()
        httpUtil.httpRequest(url, params.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                showToast("发送失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    runOnUiThread { startCountdown() }
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        showToast("验证码已发送,请注意查收！")
                        LCLogger.d(TAG, "发送成功！,信息：$jsonObject")
                    } else {
                        showToast("发送失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    cancleProgress()
                    showToast("发送失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2024/5/11  18:16
     *  @author Im_jingwei
     *  @desc 倒计时
     */
    private fun startCountdown() {
        handlerCountdown = Handler(Looper.getMainLooper())
        handlerCountdown?.postDelayed(handRunnableReped, 1000)
    }

    private val handRunnableReped = object : Runnable {
        override fun run() {
            countdown--
            runOnUiThread {
                bttCode.isEnabled = false
                bttCode.text = countdown.toString() + "秒"
            }
            if (countdown > 0) {
                handlerCountdown?.postDelayed(this, 1000)
            } else {
                countdown = 60
                bttCode.isEnabled = true
                bttCode.text = "获取验证码"
            }
        }
    }


    /**
     *  @time 2025/5/26  14:46
     *  @author Im_jingwei
     *  @desc 保存
     */
    fun submitPass(params: String) {
        val httpUtil = OkHttpUtil()
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_FINDEPASS
//        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        httpUtil.httpRequest(url, null, params, object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                showToast("操作失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    val jsonObject = JSONObject(response)
                    val success = jsonObject.getBoolean("success")
                    val msg = jsonObject.getString("message")
                    if (success) {
                        showToast("修改成功，请重新登录！")
                        clearLoginInfo()
                        LCLogger.d(TAG, "修改成功！,信息：$jsonObject")
                    } else {
                        showToast("修改失败，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    showToast("操作失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/6/7  9:05
     *  @desc 清楚登录信息，重新登录
     */
    private fun clearLoginInfo() {
        LCSPUtil.save(mContext, AppConfig.SP_ACCESS_TOKEN, "")
        LCSPUtil.save(mContext, AppConfig.SP_USER_ACCOUNT, "")
        LCSPUtil.save(mContext, AppConfig.SP_USER_PASSWORD, "")
        val intent = Intent(mContext, LoginActivity::class.java)
        startActivity(intent)
    }


}